<template>
	<view class="my-page">
		<u-navbar leftIconColor="#ffffff" :autoBack="true" :placeholder="true" bgColor="rgba(255,255,255,0.0)">
			<view slot="center" class="nav-title">
				<text v-if="status == 1">支付宝收款码设置</text>
				<text v-if="status == 2">微信收款码设置</text>
				<text v-if="status == 3">银行卡设置</text>
			</view>
		</u-navbar>
		<view class="content" v-if="status == 1">
			<view class="title">支付宝账号</view>
			<view class="item">
				<u--input color="#ffffff" placeholder="请输入支付宝账号" :readonly="payshow" border="none" v-model="pay_num"></u--input>
			</view>
			<view class="title">支付宝姓名</view>
			<view class="item">
				<u--input color="#ffffff" placeholder="请输入支付宝姓名" :readonly="payshow" border="none" v-model="pay_name"></u--input>
			</view>
			<view class="title" v-if="payshow == false">支付密码</view>
			<view class="item" v-if="payshow == false">
				<u--input color="#ffffff" type="number" placeholder="请输入支付密码" border="none" v-model="pay_password"></u--input>
			</view>
			<!-- 	<view class="item" v-if="payshow == false">
				<u-input placeholder="请输入验证码" v-model="code" border="none">
					<template slot="suffix">
						<u-code ref="uCode" @change="codeChange" seconds="60" changeText="X秒重新获取"></u-code>
						<u-button @tap="getCode" type="success" size="mini" color="rgba(0,0,0,0.0)"
							class="custom-btn"><text style="font-size: 26rpx;">{{tips}}</text></u-button>
					</template>
				</u-input>
			</view> -->
			<view class="upload" v-if="payshow == false">
				<image v-if="img == ''" @click="upLoadImg" src="../../../static/home/up-img.png" mode=""></image>
				<image v-else :src="img" @click="upLoadImg" mode=""></image>
			</view>
			<view class="upload" v-else>
				<image :src="img" mode=""></image>
			</view>
			<view class="btn" v-if="payshow == false">
				<u-button style="color: #000;" color="linear-gradient(255.89deg, #FFF0E3 6.94%, #D7B39A 87.16%)" size="large" shape="circle" type="primary"
					text="确认" @click="upAlipay"></u-button>
			</view>
		</view>
		<view class="content" v-if="status == 2">
			<view class="title">微信账号</view>
			<view class="item">
				<u--input color="#ffffff" placeholder="请输入微信账号" :readonly="payshow" border="none" v-model="vx_num"></u--input>
			</view>
			<view class="title">微信昵称</view>
			<view class="item">
				<u--input color="#ffffff" placeholder="请输入微信昵称" :readonly="payshow" border="none" v-model="vx_name"></u--input>
			</view>
			<view class="title" v-if="payshow == false">支付密码</view>
			<view class="item" v-if="payshow == false">
				<u--input color="#ffffff" type="number" placeholder="请输入支付密码" border="none" v-model="pay_password"></u--input>
			</view>
			<!-- <view class="item" v-if="payshow == false">
				<u-input placeholder="请输入验证码" v-model="code" border="none">
					<template slot="suffix">
						<u-code ref="uCode" @change="codeChange" seconds="60" changeText="X秒重新获取"></u-code>
						<u-button @tap="getCode" type="success" size="mini" color="rgba(0,0,0,0.0)"
							class="custom-btn"><text style="font-size: 26rpx;">{{tips}}</text></u-button>
					</template>
				</u-input>
			</view> -->
			<view class="upload" v-if="payshow == false">
				<image v-if="img == ''" @click="upLoadImg" src="../../../static/home/up-img.png" mode=""></image>
				<image v-else :src="img" @click="upLoadImg" mode=""></image>
			</view>
			<view class="upload" v-else>
				<image :src="img" mode=""></image>
			</view>
			<view class="btn">
				<u-button  style="color: #000;" v-if="payshow == false" color="linear-gradient(255.89deg, #FFF0E3 6.94%, #D7B39A 87.16%)" size="large"
					shape="circle" type="primary" text="确认" @click="upVx"></u-button>
			</view>
		</view>
		<view class="content" v-if="status == 3">
			<view class="title">银行卡号</view>
			<view class="item">
				<u--input color="#ffffff" placeholder="请输入银行卡号" :readonly="payshow" type="number" border="none"
					v-model="bank_num"></u--input>
			</view>
			<view class="title">持卡人姓名</view>
			<view class="item">
				<u--input color="#ffffff" placeholder="请输入持卡人姓名" :readonly="payshow" border="none" v-model="card_name"></u--input>
			</view>
			<view class="title">银行</view>
			<view class="item">
				<u--input color="#ffffff" placeholder="请输入银行(如:建设银行,农业银行)" :readonly="payshow" border="none"
					v-model="bacnk_name"></u--input>
			</view>
			<view class="title">手机号</view>
			<view class="item">
				<u--input color="#ffffff" placeholder="请输入手机号" readonly border="none" v-model="tel"></u--input>
			</view>
			<!-- <view class="item" v-if="payshow == false" >
				<u-input placeholder="请输入验证码" v-model="code" border="none">
					<template slot="suffix">
						<u-code ref="uCode" @change="codeChange" seconds="60" changeText="X秒重新获取"></u-code>
						<u-button @tap="getCode" type="success" size="mini" color="rgba(0,0,0,0.0)"
							class="custom-btn"><text style="font-size: 26rpx;">{{tips}}</text></u-button>
					</template>
				</u-input>
			</view> -->
			<view class="title" v-if="payshow == false">支付密码</view>
			<view class="item" v-if="payshow == false">
				<u--input color="#ffffff" type="number" placeholder="请输入支付密码" border="none" v-model="pay_password"></u--input>
			</view>
			<view class="btn" v-if="payshow == false">
				<u-button  style="color: #000;" color="linear-gradient(255.89deg, #FFF0E3 6.94%, #D7B39A 87.16%)" size="large" shape="circle" type="primary"
					text="确认" @click="upBank"></u-button>
			</view>
		</view>
		<compress ref="compress" />
	</view>
</template>

<script>
	import CryptoJS from 'crypto-js';
	import compress from '@/components/MarsXHChang-CavansCompressImg/compress.vue'
	export default {
		components: { 
			compress
		},
		data() {
			return {
				tips: '',
				code: '',
				status: 1,
				pay_num: '',
				pay_name: '',
				pay_password: '',
				vx_num: '',
				vx_name: '',
				bank_num: '',
				card_name: '',
				bacnk_name: '',
				tel: '',
				img: '',
				payshow: true
			}
		},
		onLoad(option) {
			this.status = option.id
			this.getInfo()
			this.getOssSign()
		},
		methods: {
			md5Encrypt(text) {
				return CryptoJS.MD5(text).toString();
			},
			codeChange(text) {
				this.tips = text;
			},
			getCode() {
				if (this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					uni.showLoading({
						title: '正在获取验证码'
					})
					setTimeout(() => {
						uni.hideLoading();
						let params = {
							phone: this.tel,
						}
						this.$Request({
							method: 'POST',
							url: '/api/login/sendRegister',
							data: params,
							ismsg: true,
						}).then(res => {
							uni.hideLoading()
							if (res.code == 1) {
								uni.$u.toast('验证码已发送');
								this.$refs.uCode.start();
							}
						})
					}, 2000);
				} else {
					uni.$u.toast('倒计时结束后再发送');
				}
			},
			getInfo() {
				let params = {
					type: this.status
				}
				this.$Request({
					method: 'POST',
					url: '/api/personal/paymentInfo',
					data: params,
					ismsg: false,
				}).then(res => {
					if (res.code == 1) {
						this.tel = res.data.tel
						if (this.status == 1) {
							if (res.data.account_num) {
								this.pay_num = res.data.account_num
								this.pay_name = res.data.name
								this.img = res.data.receive_qrcode
								this.payshow = true
							} else {
								this.payshow = false
							}
						}
						if (this.status == 2) {
							if (res.data.account_num) {
								this.vx_num = res.data.account_num
								this.vx_name = res.data.name
								this.img = res.data.receive_qrcode
								this.payshow = true
							} else {
								this.payshow = false
							}
						}
						if (this.status == 3) {
							if (res.data.bank_num) {
								this.bank_num = res.data.bank_num
								this.card_name = res.data.name
								this.bacnk_name = res.data.account_num
								this.payshow = true
							} else {
								this.payshow = false
							}
						}
					}
				})
			},
			upAlipay() {
				if (this.pay_num == '') {
					uni.showToast({
						title: '请输入支付宝账号！',
						icon: 'none'
					})
					return
				}
				if (this.pay_name == '') {
					uni.showToast({
						title: '请输入支付宝姓名！',
						icon: 'none'
					})
					return
				}
				if (this.pay_password == '') {
					uni.showToast({
						title: '请输入支付密码！',
						icon: 'none'
					})
					return
				}
				if (this.img == '') {
					uni.showToast({
						title: '请上传截图！',
						icon: 'none'
					})
					return
				}
				uni.showLoading({
					mask: true
				})
				let params = {
					account_num: this.pay_num,
					// code: this.code,
					name: this.pay_name,
					password: this.md5Encrypt(this.pay_password),
					type: this.status,
					receive_qrcode: this.img
				}
				this.$Request({
					method: 'POST',
					url: '/api/personal/paymentMethods',
					data: params,
					ismsg: true,
				}).then(res => {
					uni.hideLoading()
					if (res.code == 1) {
						this.getInfo()
					}
				})
			},
			upVx() {
				if (this.vx_num == '') {
					uni.showToast({
						title: '请输入微信账号！',
						icon: 'none'
					})
					return
				}
				if (this.vx_name == '') {
					uni.showToast({
						title: '请输入微信昵称！',
						icon: 'none'
					})
					return
				}
				if (this.pay_password == '') {
					uni.showToast({
						title: '请输入支付密码！',
						icon: 'none'
					})
					return
				}
				if (this.img == '') {
					uni.showToast({
						title: '请上传截图！',
						icon: 'none'
					})
					return
				}
				uni.showLoading({
					mask: true
				})
				let params = {
					account_num: this.vx_num,
					name: this.vx_name,
					password: this.md5Encrypt(this.pay_password),
					type: this.status,
					receive_qrcode: this.img
				}
				this.$Request({
					method: 'POST',
					url: '/api/personal/paymentMethods',
					data: params,
					ismsg: true,
				}).then(res => {
					uni.hideLoading()
					if (res.code == 1) {
						this.getInfo()
					}
				})
			},
			upBank() {
				if (this.bank_num == '') {
					uni.showToast({
						title: '请输入银行卡号！',
						icon: 'none'
					})
					return
				}
				if (this.card_name == '') {
					uni.showToast({
						title: '请输入持卡人姓名！',
						icon: 'none'
					})
					return
				}
				if (this.bacnk_name == '') {
					uni.showToast({
						title: '请输入银行！',
						icon: 'none'
					})
					return
				}
				if (this.tel == '') {
					uni.showToast({
						title: '请输入手机号！',
						icon: 'none'
					})
					return
				}
				if (this.pay_password == '') {
					uni.showToast({
						title: '请输入支付密码！',
						icon: 'none'
					})
					return
				}
				uni.showLoading({
					mask: true
				})
				let params = {
					account_num: this.bacnk_name,
					bank_num: this.bank_num,
					// code: this.code,
					mobile: this.tel,
					name: this.card_name,
					password: this.md5Encrypt(this.pay_password),
					type: 3
				}
				this.$Request({
					method: 'POST',
					url: '/api/personal/paymentMethods',
					data: params,
					ismsg: true,
				}).then(res => {
					uni.hideLoading()
					if (res.code == 1) {
						this.getInfo()
					}
				})
			},
			async upLoadImg() {
				try {
					// 1. 选择图片
					let {
						tempFilePaths
					} = await this.chooseImage();
					let filePath = tempFilePaths[0];

					uni.showLoading({
						title: '上传中...',
						mask: true
					});

					// 2. 压缩图片
					let compressParams = {
						src: filePath // 必选：要压缩的图片地址
					};

					// 等待压缩完成
					const compressedImg = await this.$refs.compress.compress(compressParams);

					// 3. 获取OSS签名
					const signData = await this.getOssSign();
					console.log(signData)
					const fileName = this.generateFileName(compressedImg); // 需要实现这个方法
					const key = `${signData.dir}${fileName}`;

					// 5. 上传到OSS
					const fileUrl = await this.uploadToOSS(compressedImg, key, signData);

					uni.showToast({
						title: '上传成功',
						icon: 'success'
					});

					this.img = fileUrl; // 返回文件URL供外部使用
				} catch (error) {
					console.error('上传失败:', error);
					uni.showToast({
						title: error.message || '上传失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},
			// 生成文件名方法（如果还没有）
			generateFileName(filePath) {
			  // 获取干净的文件名（不含路径）
			  const filename = filePath.split('/').pop(); // 获取最后一部分
			  
			  // 提取纯净的扩展名（去掉查询参数等）
			  let extension = 'jpg'; // 默认值
			  const match = filename.match(/\.([a-z0-9]+)(?:\?|$)/i);
			  if (match) {
			    extension = match[1].toLowerCase();
			  }
			  
			  // 生成格式化的日期时间字符串
			  const now = new Date();
			  const year = now.getFullYear();
			  const month = String(now.getMonth() + 1).padStart(2, '0');
			  const day = String(now.getDate()).padStart(2, '0');
			  const hours = String(now.getHours()).padStart(2, '0');
			  const minutes = String(now.getMinutes()).padStart(2, '0');
			  const seconds = String(now.getSeconds()).padStart(2, '0');
			  const milliseconds = String(now.getMilliseconds()).padStart(3, '0');
			  
			  // 添加随机字符串确保唯一性
			  const randomStr = Math.random().toString(36).substring(2, 6);
			  
			  // 组合成文件名：YYYYMMDD_HHMMSSmmm_xxxx.扩展名
			  return `${year}${month}${day}_${hours}${minutes}${seconds}${milliseconds}_${randomStr}.${extension}`;
			},
			// 封装选择图片方法
			chooseImage() {
				return new Promise((resolve, reject) => {
					uni.chooseImage({
						count: 1,
						sizeType: ['compressed'], // 尝试压缩
						sourceType: ['album'],
						success: resolve,
						fail: (err) => {
							console.error('选择图片失败:', err);
							reject(new Error('选择图片失败，请重试'));
						}
					});
				});
			},

			// 获取OSS签名方法
			async getOssSign() {
				try {
					let res = await this.$Request({
						method: 'GET',
						url: '/api/upload/ossSign',
						data: {},
						ismsg: false
					});

					if (res.code === 1) {
						return res;
					} else {
						throw new Error(res.msg || '获取上传凭证失败');
					}
				} catch (error) {
					console.error('获取OSS签名失败:', error);
					throw new Error('获取上传凭证失败，请检查网络');
				}
			},


			uploadToOSS(filePath, key, signData) {
				return new Promise((resolve, reject) => {
					const uploadTask = uni.uploadFile({
						url: signData.host, // 确保host不带结尾斜杠
						filePath: filePath,
						name: 'file',
						formData: {
							key: key,
							policy: signData.policy,
							OSSAccessKeyId: signData.accessid,
							success_action_status: '200',
							signature: signData.signature
						},
						success: (res) => {
							if (res.statusCode === 200) {
								// 正确拼接URL方式：
								const host = signData.host.replace(/\/+$/, ''); // 移除host末尾的斜杠
								const cleanKey = key.replace(/^\/+/, ''); // 移除key开头的斜杠
								console.log(`${host}/${cleanKey}`)
								resolve(`${host}/${cleanKey}`); // 单斜杠连接
								
							} else {
								reject(new Error(`上传失败，状态码: ${res.statusCode}`));
							}
						},
						fail: (err) => {
							reject(new Error('文件上传失败，请检查网络连接'));
						}
					});
				});
			}
		}
	}
</script>

<style>
	.custom-btn {
		color: red !important;
	}
	page{
		background: #000000;
	}
</style>
<style lang="scss" scoped>
	.my-page {
		height: 100vh;
		position: relative;
		background-image: url('../../../static/login/login-bg.png');
		background-repeat: no-repeat;
		background-size: 100% 593px;
		padding: 30rpx;

		.nav-title {
			color: #ffffff;
		}

		.content {
			padding: 30rpx;
			border-radius: 30rpx;
			.title{
				color: #ffffff;
				margin-bottom: 20rpx;
				font-size: 26rpx;
			}
			.item {
				background-color: #1A1A1B;
				margin-bottom: 30rpx;
				padding: 30rpx;
				border-radius: 30rpx;
			}

			.upload {
				text-align: center;
				margin-top: 20rpx;
				
				image {
					width: 280rpx;
					height: 280rpx;
				}
			}

			.btn {
				margin-top: 30rpx;
			}
		}
	}
</style>